﻿using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.CommonStr;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models;
using ELearning.Models.ViewModel;
using ELearning.Models.ViewModel.Message;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Transactions;
using System.Web;
using System.Web.Http;

namespace ELearning.API.Controllers.AdminControllers
{
    /// <summary>
    /// 订单信息
    /// </summary>
    public class OrderController : BaseApiController
    {
        EBuyRecordService orderService = new EBuyRecordService();
        EOrderService orderser = new EOrderService();
        RClassProductService classProductService = new RClassProductService();
        private ECourseSeriesService courseSeriesService = new ECourseSeriesService();
        private EStudentStudySumService eStudentStuSumService = new EStudentStudySumService();
        #region 订单数据

        /// <summary>
        /// 获取搜索订单信息
        /// </summary>
        /// <returns></returns>
        [Route("api/order/searchOrderList")]
        [HttpGet]
        public object SearchOrderList(string orderNo, string title, string isPay, string confirm)
        {
            var orgCode = CurrentUserModel.OrgCode;
            var orders = orderService.GetOrderList(orgCode, orderNo, title, isPay, confirm);

            return ServiceResponse<object>.SuccessResponse(orders);
        }

        /// <summary>
        /// 更新订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [Route("api/order/updateOrder")]
        [HttpPost]
        public object UpdateOrder(string orderId)
        {
            var ordid = Guid.Parse(orderId);
            Expression<Func<EOrder, bool>> explist = null;
            explist = u => u.ID == ordid;
            var order = orderser.Find(explist);
            order.IsPay = true;
            order.PayDate = DateTime.Now;
            order.ModifyTime = DateTime.Now;
            order.Modifyer = CurrentUserModel.LoginName;
            var r = orderser.Update(order);

            if (r) return ServiceResponse<object>.SuccessResponse("订单支付成功");
            else return ServiceResponse<object>.ErrorResponse("订单支付失败");
        }

        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [Route("api/order/deleteOrder")]
        [HttpPost]
        public object DeleteOrder(string orderId)
        {
            var ordid = Guid.Parse(orderId);
            Expression<Func<EOrder, bool>> explist = null;
            explist = u => u.ID == ordid;
            var order = orderser.Find(explist);
            order.IsDelete = true;
            var r = orderser.Update(order);

            if (r) return ServiceResponse<object>.SuccessResponse("删除订单成功");
            else return ServiceResponse<object>.ErrorResponse("删除订单失败");
        }

        #endregion

        #region 产品分配班级数据

        /// <summary>
        /// 获取当前已分配的班级信息
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        [Route("api/order/searchProductCls")]
        [HttpGet]
        public object SearchProductCls(string productId, string className)
        {
            var clss = orderService.GetProductCls(productId, className);

            return ServiceResponse<object>.SuccessResponse(clss);
        }

        /// <summary>
        /// 获取当前班级信息-未分配
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        [Route("api/order/searchProductClsOther")]
        [HttpGet]
        public object SearchProductClsOther(string productId, string className)
        {
            var orgCode = CurrentUserModel.OrgCode;
            var clss = orderService.GetProductClsOther(orgCode, productId, className);

            return ServiceResponse<object>.SuccessResponse(clss);
        }

        /// <summary>
        /// 产品分配予班级-批量
        /// </summary>
        /// <param name="clss"></param>
        /// <param name="productId"></param>
        /// <returns></returns>
        [Route("api/order/insertProductCls")]
        [HttpPost]
        public object InsertProductCls(List<EClass> clss, string productId)
        {
            var pid = Guid.Parse(productId);
            List<RClassProduct> clspro = new List<RClassProduct>();
            RClassProduct clsp = null;
            foreach (var u in clss)
            {
                clsp = new RClassProduct();
                clsp.ID = Guid.NewGuid();
                clsp.ClassID = u.ClassID;
                clsp.ProductID = pid;
                clsp.OrgCode = CurrentUserModel.OrgCode;
                clsp.Creater = CurrentUserModel.LoginName;
                clsp.CreateTime = DateTime.Now;
                clsp.Modifyer = CurrentUserModel.LoginName;
                clsp.ModifyTime = DateTime.Now;

                clspro.Add(clsp);
            }

            var r = classProductService.Adds(clspro);
            if (r == clss.Count) return ServiceResponse<object>.SuccessResponse("分配予班级成功");
            else if (r > 0) return ServiceResponse<object>.SuccessResponse("分配予班级成功" + r + "个" + "；失败" + (clss.Count - r) + "个");
            else return ServiceResponse<object>.ErrorResponse("分配予班级失败");
        }

        /// <summary>
        /// 移除已分配的班级
        /// </summary>
        /// <returns></returns>
        [Route("api/order/deleteProductCls")]
        [HttpPost]
        public object DeleteProductCls(List<EClass> clss, string productId)
        {
            var clsId = clss.Select(u => u.ClassID).ToList();
            var arr = string.Join(",", clsId);
            arr = arr.Replace(",", "','");
            arr = "'" + arr + "'";

            var r = orderService.DeleteClassProduct(arr, productId);

            if (r == clss.Count) return ServiceResponse<object>.SuccessResponse("移除学生成功");
            else if (r > 0) return ServiceResponse<object>.SuccessResponse("移除班级成功" + r + "个" + "；失败" + (clss.Count - r) + "个");
            else return ServiceResponse<object>.ErrorResponse("移除班级失败");
        }

        #endregion

        protected EOrderService oService = new EOrderService();
        protected EProductService productService = new EProductService();
        protected EOrgService orgService = new EOrgService();
        protected EOrderProductDetailService opService = new EOrderProductDetailService();
        protected RCSUserSignedService rCSUserSignedService = new RCSUserSignedService();
        protected EMessageService eMessageService = new EMessageService();
        protected RMessageUserService rMessageUserService = new RMessageUserService();
        protected ESysUserService eSysUserService = new ESysUserService();

        [HttpPost, Route("api/Order/GetBuyRecordList")]
        public ServiceResponse<OrderModel> GetBuyRecordList(GetOrderRequest request)
        {
            var viewModel = new OrderModel();
            var buyPage = oService.GetOrderList(request);
            if (buyPage != null)
            {
                foreach (var buy in buyPage.Items)
                {
                    var u = new OrderItem
                    {
                        ID = buy.ID,
                        OrderNo = buy.OrderNo,
                        CreateTime = buy.CreateTime,
                        Creater = buy.Creater,
                        ConfirmStatus = buy.ConfirmStatus,
                        Description = buy.Description,
                        IsPay = buy.IsPay,
                        Buyer = buy.Buyer,
                        ModifyTime = buy.ModifyTime,
                        OrgCode = buy.OrgCode,
                        OrgName = orgService.Find(w => w.org_code == buy.OrgCode)?.org_name,
                        IsDelete = buy.IsDelete
                    };
                    //if (!string.IsNullOrEmpty(request.OrgName))
                    //{
                    //    if (u.OrgName.Contains(request.OrgName))
                    //    {
                    //        viewModel.OrderItems.Add(u);
                    //    }
                    //}
                    //else
                    //{
                    //    viewModel.OrderItems.Add(u);
                    //}
                    viewModel.OrderItems.Add(u);
                }
                viewModel.TotalCount = buyPage.TotalItems.ObjToInt();
            }
            return ServiceResponse<OrderModel>.SuccessResponse("success", viewModel);
        }

        [HttpGet, Route("api/Order/changeBuyStatus")]
        public ServiceResponse<OrderItem> changeBuyStatus(string id, string state = "stoped")
        {
            var buy = oService.Find(w => w.ID.ToString() == id);
            var u = new OrderItem
            {
                ID = buy.ID,
                OrderNo = buy.OrderNo,
                CreateTime = buy.CreateTime,
                Creater = buy.Creater,
                ConfirmStatus = buy.ConfirmStatus,
                Description = buy.Description,
                IsPay = buy.IsPay,
                Buyer = buy.Buyer,
                ModifyTime = buy.ModifyTime,
                OrgCode = buy.OrgCode,
                OrgName = orgService.Find(w => w.org_code == buy.OrgCode)?.org_name,
                IsDelete = buy.IsDelete
            };
            buy.ConfirmStatus = buy.IsPay ? 1 : 2;
            buy.IsPay = !buy.IsPay;
            if (buy.IsPay)
            {
                buy.PayDate = DateTime.Now;
            }
            bool b = oService.Update(buy);
            if (b)
            {
                u.ConfirmStatus = buy.ConfirmStatus;
                u.IsPay = buy.IsPay;
                return ServiceResponse<OrderItem>.SuccessResponse("操作成功", u);
            }
            else
            {
                return ServiceResponse<OrderItem>.SuccessResponse("操作失败", u);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="orderno"></param>
        /// <returns></returns>
        [HttpGet, Route("api/Order/getOrderDetailByOrderNo")]
        public ServiceResponse<List<EOrderProductDetail>> getOrderDetailByOrderNo(string orderno)
        {
            Expression<Func<EOrderProductDetail, bool>> explist = null;
            explist = u => u.IsDelete == false && u.OrderNo == orderno;
            var orderlist = opService.FindList(explist, "CreateTime", true).ToList();
            return ServiceResponse<List<EOrderProductDetail>>.SuccessResponse("操作成功!", orderlist);
        }

        [HttpGet, Route("api/Order/DeleteOrderInfo")]
        public object DeleteOrderInfo(string orderId)
        {
            var ordid = Guid.Parse(orderId);
            Expression<Func<EOrder, bool>> explist = null;
            explist = u => u.ID == ordid;
            var order = oService.Find(explist);
            order.IsDelete = true;
            var r = oService.Update(order);

            Expression<Func<EOrderProductDetail, bool>> expoproductlist = null;
            expoproductlist = u => u.OrderID == ordid;
            var orderproduct = opService.Find(expoproductlist);
            orderproduct.IsDelete = true;
            var rr = opService.Update(orderproduct);
            if (r && rr) return ServiceResponse<bool>.SuccessResponse("操作成功!", r);
            else return ServiceResponse<bool>.ErrorResponse("删除订单失败", r);
        }

        /// <summary>
        /// 按照 课程产品ID 查询报名列表
        /// </summary>
        /// <param name="csID"></param>
        /// <returns></returns>
        [HttpPost, Route("api/Order/GetCourseUserList")]
        public ServiceResponse<OrderModel> GetCourseUserList(string csID)
        {
            var viewModel = new OrderModel();
            var orderList = oService.GetOrderListByCSID(csID);
            if (orderList != null)
            {
                foreach (var buy in orderList)
                {
                    var u = new OrderItem
                    {
                        ID = buy.ID,
                        OrderNo = buy.OrderNo,
                        CreateTime = buy.CreateTime,
                        Creater = buy.Creater,
                        ConfirmStatus = buy.ConfirmStatus,
                        Description = buy.Description,
                        IsPay = buy.IsPay,
                        Buyer = buy.Buyer,
                        ModifyTime = buy.ModifyTime,
                        OrgCode = buy.OrgCode,
                        OrgName = orgService.Find(w => w.org_code == buy.OrgCode)?.org_name,
                        IsDelete = buy.IsDelete
                    };
                    viewModel.OrderItems.Add(u);
                }
                viewModel.TotalCount = orderList.Count;
            }
            return ServiceResponse<OrderModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 按照 课程产品ID 查询已报名列表
        /// </summary>
        /// <param name="csID"></param>
        /// <returns></returns>
        [HttpGet, Route("api/Order/GetConfirmCourseUserList")]
        public ServiceResponse<CSUserViewModel> GetConfirmCourseUserList(string csID)
        {
            if (string.IsNullOrWhiteSpace(csID))
            {
                return null;
            }
            Guid gId = Guid.Parse(csID);

            var viewModel = new CSUserViewModel();
            var orderList = oService.GetConfirmOrderListByPRID(gId);
            if (orderList != null)
            {
                var product = productService.Find(p => p.PRID == gId);
                viewModel.IsSignUp = product == null ? false : product.StartTime < DateTime.Now;
                viewModel.CSUserItems = orderList;
                viewModel.SignedCount = orderList.Count(t => t.ConfirmStatus == 2 && t.IsSigned);
                viewModel.TotalCount = orderList.Count(t => t.ConfirmStatus == 2);
            }
            return ServiceResponse<CSUserViewModel>.SuccessResponse("success", viewModel);
        }

        /// <summary>
        /// 保存报名信息
        /// </summary>
        /// <param name="csUserList"></param>
        /// <returns></returns>
        [HttpPost, Route("api/Order/SetConfirmCourseUserList")]
        public ServiceResponse<string> SetConfirmCourseUserList(List<CSUserItem> csUserList)
        {
            if (csUserList == null)
            {
                return ServiceResponse<string>.WarningResponse("操作失败！");
            }

            var pridlist = csUserList.Select(w => w.CSID).ToList();
            var productlist = productService.FindList(w => pridlist.Contains(w.ID));
            var csID = csUserList.Select(c => c.CSID).FirstOrDefault();
            var orderList = oService.GetConfirmOrderListByCSID(csID);
            var product = productService.Find(p => p.ID == csID);
            #region 验证

            #endregion
            if (product.IsNull())
            {
                //课程不存在
                return ServiceResponse<string>.WarningResponse("课程不存在！");
            }
            if (product.ApplicantSTime > DateTime.Now)
            {
                return ServiceResponse<string>.WarningResponse("报名尚未开始！");
            }
            if (product.ApplicantETime > DateTime.Now)
            {
                return ServiceResponse<string>.WarningResponse("报名尚未结束！");
            }
            //if (product.StartTime < DateTime.Now)
            //{
            //    return ServiceResponse<string>.WarningResponse("课程已开始，不可进行报名修改！");
            //}
            if (product.ApplicantCount < csUserList.Count(c => c.ConfirmStatus == 2))
            {
                return ServiceResponse<string>.WarningResponse(string.Format("报名人数不可超过{0}人！", product.ApplicantCount));
            }
            var csid = product.PRID;
            using (var trans = new TransactionScope())
            {
                foreach (var item in csUserList)
                {
                    MessageSendRespViewModel msg = new MessageSendRespViewModel();
                    var o = orderser.Find(t => t.ID == item.ID);
                    if (o.IsNull())
                    {
                        //数据已删除，无须处理
                        continue;
                    }
                    o.ConfirmStatus = item.ConfirmStatus;
                    var user = eSysUserService.Find(u => u.UserID == item.BuyUserID);
                    if (user.IsNull())
                    {
                        //用户不存在
                        continue;
                    }
                    #region Message

                    var emsg = new EMessage()
                    {
                        Id = GuidUtil.NewSequentialId(),
                        CreateTime = DateTime.Now,
                        Creater = CurrentUserModel?.LoginName ?? string.Empty,
                        IsDelete = false,
                        IsStick = DateTime.Now,
                        ModifyTime = DateTime.Now,
                        Modifyer = CurrentUserModel?.LoginName ?? string.Empty,
                        ReadCount = 0,
                        SendTime = DateTime.Now,
                        State = 3,
                        Type = 2,
                        Title = "报名通知",
                        SubTitle = "报名通知",
                        Text = string.Format(AppConfig.ApplyFail, product.Title)
                    };
                    var msgUser = new RMessageUser()
                    {
                        Id = GuidUtil.NewSequentialId(),
                        Creater = CurrentUserModel?.LoginName ?? string.Empty,
                        CreateTime = DateTime.Now,
                        CSId = csID,
                        MessageId = emsg.Id,
                        UserId = item.BuyUserID,
                        IsDelete = false
                    };
                    #endregion

                    if (item.ConfirmStatus == 2)
                    {
                        #region Success Message

                        emsg.Text = string.Format(AppConfig.ApplySuccess, product.Title);
                        msgUser.ApplicantStatus = 1;
                        //msg = SendMsg(o, user, product, emsg.Text);
                        //o.MsgStatus = msg.status ? "1" : "0";
                        //o.MsgEror = string.IsNullOrWhiteSpace(msg.msg) ? "" : msg.msg.Length < 50 ? msg.msg : msg.msg.Substring(0, 50);
                        o.MsgID = emsg.Id;
                        o.IsPay = true;
                        eMessageService.Add(emsg);
                        rMessageUserService.Add(msgUser);
                        orderser.Update(o);
                        var stuList = new List<Guid>();
                        stuList.Add(o.BuyUserID);
                        #endregion

                        #region  插入学习记录信息 用于在用户中心显示课程信息
                        var study = eStudentStuSumService.Find(w => w.StuID == item.BuyUserID && w.CSID == csid);
                        if (study != null)
                        {
                            study.IsDelete = false;
                            study.percentage = 0;
                            eStudentStuSumService.Update(study);
                        }
                        else
                        {
                            var studentstudy = new EStudentStudySum
                            {
                                ID = GuidUtil.NewSequentialId(),
                                StuID = item.BuyUserID,
                                CSID = csid,
                                overcount = 0,
                                countsum = courseSeriesService.GetCourseCountById(csid),
                                percentage = 0,
                                StudyMinute = 0,
                                Creater = CurrentUserModel.LoginName,
                                CreateTime = DateTime.Now,
                                EndTime = DateTime.Now,
                                StartTime = DateTime.Now,
                                IsDelete = false,
                                Modifyer = CurrentUserModel.LoginName,
                                ModifyTime = DateTime.Now
                            };
                            eStudentStuSumService.Add(studentstudy);
                        }
                        #endregion
                    }
                    else
                    {
                        if (item.ConfirmStatus == 3)
                        {
                            #region Fail Message
                            emsg.Text = string.Format(AppConfig.ApplyFail, product.Title);
                            msgUser.ApplicantStatus = 2;
                            emsg.State = 3;
                            ////发送通知
                            //msg = SendMsg(o, user, product, emsg.Text);
                            //o.MsgStatus = msg.status ? "1" : "0";
                            //o.MsgEror = string.IsNullOrWhiteSpace(msg.msg) ? "" : msg.msg.Length < 50 ? msg.msg : msg.msg.Substring(0, 50);
                            o.MsgID = emsg.Id;
                            eMessageService.Add(emsg);
                            rMessageUserService.Add(msgUser);
                            #endregion
                        }
                        o.IsPay = false;
                        orderser.Update(o);

                        #region 删除学习进度
                        var studentstudy = eStudentStuSumService.Find(w => w.StuID == item.BuyUserID && w.CSID == csid);
                        if (studentstudy != null)
                            eStudentStuSumService.Delete(studentstudy);
                        #endregion

                        #region 删除作业

                        var stuList = new List<Guid>();
                        stuList.Add(o.BuyUserID);
                        #endregion
                    }
                }
                trans.Complete();
            }

            return ServiceResponse<string>.SuccessResponse("success", "操作成功");
        }
        /// <summary>
        /// 发送销售助手、骏客消息
        /// </summary>
        /// <param name="o"></param>
        /// <param name="user"></param>
        /// <param name="product"></param>
        /// <param name="msgContent"></param>
        /// <returns></returns>
        [Obsolete("改用Job发送消息2019-11-21")]
        private MessageSendRespViewModel SendMsg(EOrder o, ESysUser user, EProduct product, string msgContent)
        {
            var msg = new MessageSendRespViewModel();
            if (user.UserType == UserType.UserTypeSTUDENT)
            {
                //发送通知
                msg = eMessageService.SendMsg("", msgContent, user.Unumber);
            }
            else if (user.UserType == UserType.UserTypeSTUDENT)
            {
                var res = eMessageService.SendXszsMsg("", msgContent, user.Unumber, user.UserName, product.Title, o.ID.ToString());
                msg.status = res.success;
                msg.msg = res.error;
            }
            return msg;
        }

        /// <summary>
        /// 保存签到数据
        /// </summary>
        /// <param name="csUserList"></param>
        /// <returns></returns>
        [HttpPost, Route("api/Order/SetSignedCourseUserList")]
        public ServiceResponse<string> SetSignedCourseUserList(List<CSUserItem> csUserList)
        {
            if (csUserList == null)
            {
                return ServiceResponse<string>.WarningResponse("操作失败");
            }
            var csID = csUserList.Select(c => c.CSID).FirstOrDefault();
            var orderList = oService.GetConfirmOrderListByCSID(csID);
            var rCSUserList = rCSUserSignedService.FindList(r => r.CSID == csID);
            var dRCSUserList = new List<RCSUserSigned>();
            foreach (var item in csUserList)
            {
                var o = orderList.FirstOrDefault(t => t.CSID == item.CSID && t.BuyUserID == item.BuyUserID);
                if (o.IsNull())
                {
                    //数据已删除，无须处理
                    continue;
                }
                var r = rCSUserList.FirstOrDefault(t => t.CSID == item.CSID && t.UserID == item.BuyUserID);
                if (r.IsNotNull())
                {
                    r.IsSigned = item.IsSigned;
                    rCSUserSignedService.Update(r);
                    dRCSUserList.Add(r);
                }
                else
                {
                    r = new RCSUserSigned()
                    {
                        ID = Guid.NewGuid(),
                        CSID = item.CSID,
                        UserID = item.BuyUserID,
                        IsSigned = item.IsSigned
                    };
                    rCSUserSignedService.Add(r);
                    dRCSUserList.Add(r);
                }
            }
            foreach (var item in rCSUserList)
            {
                var o = dRCSUserList.FirstOrDefault(t => t.CSID == item.CSID && t.UserID == item.UserID);
                if (o.IsNull())
                {
                    rCSUserSignedService.Delete(o);
                }
            }
            return ServiceResponse<string>.SuccessResponse("success", "操作成功");
        }

        /// <summary>
        /// 更改报名状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="bFlag"></param>
        /// <returns></returns>
        [HttpGet, Route("api/Order/SetSigned")]
        public ServiceResponse<OrderItem> SetSigned(string id, bool bFlag)
        {
            var buy = oService.Find(w => w.ID.ToString() == id);
            buy.ConfirmStatus = bFlag ? 1 : 2;
            buy.ModifyTime = DateTime.Now;
            bool b = oService.Update(buy);
            var u = new OrderItem
            {
                ID = buy.ID,
                OrderNo = buy.OrderNo,
                CreateTime = buy.CreateTime,
                Creater = buy.Creater,
                ConfirmStatus = buy.ConfirmStatus,
                Description = buy.Description,
                IsPay = buy.IsPay,
                Buyer = buy.Buyer,
                ModifyTime = buy.ModifyTime,
                OrgCode = buy.OrgCode,
                OrgName = orgService.Find(w => w.org_code == buy.OrgCode)?.org_name,
                IsDelete = buy.IsDelete
            };

            if (b)
            {
                u.ConfirmStatus = buy.ConfirmStatus;
                u.IsPay = buy.IsPay;
                return ServiceResponse<OrderItem>.SuccessResponse("操作成功", u);
            }
            else
            {
                return ServiceResponse<OrderItem>.SuccessResponse("操作失败", u);
            }

        }


        [HttpPost, Route("api/Order/SetManPass")]
        public ServiceResponse<bool> SetManPass(CSUserItem csUser)
        {
            bool b = false;
            var product = productService.Find(w => w.ID == csUser.CSID);
            if (product != null)
            {
                var csid = product.PRID;
                var study = eStudentStuSumService.Find(w => w.StuID == csUser.BuyUserID && w.CSID == csid);
                if (study != null)
                {
                    study.IsDelete = false;
                    study.percentage = csUser.percentage == 100 ? 0 : 100;
                    study.Modifyer = CurrentUserModel.LoginName;
                    study.ModifyTime = DateTime.Now;
                    b = eStudentStuSumService.Update(study);
                }
            }
            return ServiceResponse<bool>.SuccessResponse(CommonConst.OprateSuccessStr, b);
        }

    }
}